<template>
    <section class="modlude">
      <el-form :inline="true" :model="formSearch" class="form_inline" label-width="80px" size="small">
        <!-- <el-form-item label="所属组织">
          <el-cascader
            ref="cascader"
            v-model="option1"
            :options="dataTree"
            :props="defaultProps2"
            @change="handleChange"
            clearable
          >
          </el-cascader>
        </el-form-item> -->
        <el-form-item label="账号">
          <el-input v-model="formSearch.account" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="formSearch.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="formSearch.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formSearch.enable" placeholder="请选择状态">
            <el-option label="禁用" :value="0"></el-option>
            <el-option label="启用" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item size="small">
          <el-button  @click="getlist" >查 询</el-button>
          <!-- v-if="$root.btnControl.find(item=>item=='add')" -->
          <el-button  @click="addDialog = true,imageUrl = '',isAddUpdata=1" >新 增
          </el-button>
        </el-form-item>
      </el-form>
      <el-table :data="formData" style="width: 100%" stripe>
        <el-table-column prop="account" label="账号"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <!-- <el-table-column prop="avatar" label="头像" width="100">
                  <template slot-scope="scope">
            <el-image style="width: 70px; height: 70px" :src="scope.row.avatar" fit="cover"></el-image>
                  </template>
        </el-table-column> -->
        <!-- <el-table-column prop="orgName" label="所属组织"></el-table-column> -->
        <el-table-column prop="phone" label="号码"></el-table-column>
        <el-table-column label="性别">
          <template slot-scope="scope">
            {{ scope.row.sex == 2 ? "女" : scope.row.sex == 1 ? "男" : '未知' }}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            {{ scope.row.enable == 1 ? "启用" : '禁用' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width=350>
          <template slot-scope="scope">
            <!-- <el-button size="small" @click="showRole(scope.row)" v-if="$root.btnControl.find(item=>item=='manager_bind_role')">角色绑定
            </el-button> -->
            <el-button type="" size="small" @click="updateShowBox(scope.row),isUpdataPo=false,isAddUpdata=3">详 情
            </el-button>
            <!-- v-if="$root.btnControl.find(item=>item=='edit')" -->
            <el-button type="warning" size="small" @click="updateShowBox(scope.row),isUpdataPo=true,isAddUpdata=2" >修 改
            </el-button>
            
  <!-- v-if="$root.btnControl.find(item=>item=='delete')" -->
            <el-button type="danger" size="small" @click="deleInfor(scope.row.id)" >删 除
            </el-button>
            <el-button size="small" @click="resetPasswords(scope.row.id)" >重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <paging @changePage=handleCurrentPage :get-total='total'></paging>
      <div class="export_template" style="margin-bottom:20px;">
        <!-- <el-button size="small" @click="exportTemplate" type="primary" round>导出模板</el-button> -->
        <!-- <el-button size="small" @click="getLabel" type="warning" round>
          导出数据
        </el-button> -->
        <!-- <el-button size="small" @click="showImport=true" type="success" round v-if="$root.btnControl.find(item=>item=='import')">导入数据</el-button> -->
      </div>
      <!-- 添加 -->
      <el-dialog title="新增" :visible.sync="addDialog" :close-on-click-modal="false">
        <div class="cont_box_right">
          <el-form label-position="right" :inline="true" :rules="rules" label-width="110px" :model="formPush"
                   ref='addList'>
            <el-form-item label="账号" size="small" prop="account">
              <el-input v-model="formPush.account"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name" size="small">
              <el-input v-model="formPush.name"></el-input>
            </el-form-item>
            <el-form-item label="号码" size="small" prop="phone">
              <el-input v-model="formPush.phone"></el-input>
            </el-form-item>
            <el-form-item label="密码" size="small" prop="password">
              <el-input v-model="formPush.password"></el-input>
            </el-form-item>
            <!-- <el-form-item label="所属组织" size="small" prop="orgId">
              <el-cascader
                ref="cascader"
                v-model="option1"
                :options="dataTree"
                :props="defaultProps2"
                @change="handleChange1"
              >
              </el-cascader>
            </el-form-item> -->
            <el-form-item label="邮箱" size="small">
              <el-input v-model="formPush.email"></el-input>
            </el-form-item>
            <!-- <el-form-item label="备注" size="small">
              <el-input v-model="formPush.description"></el-input>
            </el-form-item> -->
            <el-form-item label="性别" size="small" prop="sex">
              <el-radio v-model="formPush.sex" :label="2">女</el-radio>
              <el-radio v-model="formPush.sex" :label="1">男</el-radio>
              <el-radio v-model="formPush.sex" :label="0">未知</el-radio>
            </el-form-item>
            <el-form-item label="是否启用" size="small" prop="enable">
              <el-radio v-model="formPush.enable" :label="true">启用</el-radio>
              <el-radio v-model="formPush.enable" :label="false">禁用</el-radio>
            </el-form-item>
            <el-form-item label="用户角色" size="small" prop="floors">
                <el-select v-model="formPush.roles" multiple  placeholder="请选择角色">
                  <el-option v-for="item in rolesList" :key="item.lable" :label="item.name" :value="item.lable"></el-option>
                </el-select>
              </el-form-item>
            <el-form-item label="头像" size="small">
              <el-upload
                ref="addUpdata"
                class="avatar-uploader"
                action="/api/v1.0/file/upload/file"
                :show-file-list="false"
                :headers='headers'
                :on-change="onChange"
                :on-success="handleAvatarSuccess">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="medium " @click="addDialog = false">取 消</el-button>
          <el-button size="medium " @click="addList('addList')">新 增</el-button>
        </div>
      </el-dialog>
      <!-- 修改 -->
      <el-dialog :title="isUpdataPo?'修改':'详情'" :visible.sync="updateDialog" :close-on-click-modal="false">
        <div class="cont_box_right">
          <el-form label-position="right" :inline="true" :rules="rules" label-width="110px" :model="formUpdate"
                   ref='formUpdate'>
            <el-form-item label="账号" size="small" prop="account">
              <el-input v-model="formUpdate.account"></el-input>
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="formUpdate.name"></el-input>
            </el-form-item>
            <el-form-item label="号码" size="small">
              <el-input v-model="formUpdate.phone"></el-input>
            </el-form-item>
            <!-- <el-form-item label="密码" size="small" prop="password">
              <el-input v-model="formUpdate.password"></el-input>
            </el-form-item> -->
            <!-- <el-form-item label="备注">
              <el-input v-model="formUpdate.description"></el-input>
            </el-form-item> -->
            <el-form-item label="邮箱" size="small">
              <el-input v-model="formUpdate.email"></el-input>
            </el-form-item>
            <el-form-item label="性别" size="small" prop="sex">
              <el-radio v-model="formUpdate.sex" :label="2">女</el-radio>
              <el-radio v-model="formUpdate.sex" :label="1">男</el-radio>
              <el-radio v-model="formUpdate.sex" :label="0">未知</el-radio>
            </el-form-item>
            <el-form-item label="是否启用" size="small" prop="enable">
              <el-radio v-model="formUpdate.enable" :label="true">启用</el-radio>
              <el-radio v-model="formUpdate.enable" :label="false">禁用</el-radio>
            </el-form-item>
            <el-form-item label="用户角色" size="small" prop="">
                <el-select v-model="formUpdate.roles" multiple  placeholder="请选择角色">
                  <el-option v-for="item in rolesList" :key="item.lable" :label="item.name" :value="item.lable"></el-option>
                </el-select>
              </el-form-item>
            <el-form-item label="头像" size="small">
              <el-upload
                ref="addUpdata"
                class="avatar-uploader"
                action="/api/v1.0/file/upload/file"
                :show-file-list="false"
                :headers='headers'
                :on-change="onChange"
                :on-success="handleAvatarSuccess">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-form>
  
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="medium " @click="updateDialog = false">取 消</el-button>
          <el-button size="medium " @click="updateList('formUpdate')" v-if="isUpdataPo">修 改</el-button>
        </div>
      </el-dialog>
      <!-- 角色绑定 -->
      <el-dialog title="角色绑定" :visible.sync="dialog" width="1000px">
        <div class="cont_box_right">
          <el-form label-position="right" label-width="50px" :model="bindRole" ref='bindRole'>
            <el-form-item label="角色" size="small">
              <el-row >
                <el-col :span="8">
                  <el-tree
                    :data="formDataa"
                    :props='defaultProps'
                    :load="loadNode"
                    lazy
                    node-key="id"
                    :check-strictly="checkStrictly"
                    show-checkbox
                    :default-expanded-keys="showmenuList"
                    :default-checked-keys="showmenuList"
                    @check="handleCheckChange"
                    @node-click="treeClick"
                    :filter-node-method="filterNode"
                    :expand-on-click-node="false">
                    <div class="custom-tree-node" slot-scope="{ node, data }">
                      <span>{{ node.label }}</span>
                    </div>
                  </el-tree>
                </el-col>
                <el-col :span="8">
                  <el-tree
                    :data="menuList1"
                    :props='defaultProps1'
                    :default-expanded-keys="showmenuList1"
                    :default-checked-keys="showmenuList1"
                    node-key="id"
                    ref="rightsTree1"
                    :filter-node-method="filterTree"
                    @node-click="nodeClick"
                  >
                  </el-tree>
                </el-col>
                <el-col :span="8">
                  <el-table :data="buttonList" stripe ref="multipleTable">
                    <el-table-column prop="code" label="code" show-overflow-tooltip/>
                    <el-table-column prop="name" label="名称"/>
                  </el-table>
                </el-col>
              </el-row>
  
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="medium " @click="dialog = false">取 消</el-button>
          <el-button size="medium " @click="bindroleManage()">绑 定</el-button>
        </div>
      </el-dialog>
      <!-- 导出数据 -->
      <el-dialog title="导出" :visible.sync="showExport">
        <exportInfor @getexportHouseUser="getexportHouseUser" @closeDialog="closeDialog"
                     :typeExport="typeExport"></exportInfor>
      </el-dialog>
    </section>
  </template>
  
  <script>
  import paging from "../../components/paging"
  import base64 from 'js-base64';
  import exportInfor from "../../components/export_infor"
  import {getDateArray} from '../../util/util'
  import {
    userReset,
    exportHouseManager,
    userListPage,
    userAdd,
    userUpdate,
    userDelete,
    xqSelectList,
    orgTree,
    managerrole,
    bindmanagerrole,
    roletreeList,
    menuList,
    bindmenuroleId,
  } from '../../url/api';
  
  export default {
    created() {
      console.log(this.$root.btnControl);
  
    },
    data() {
      return {
        rolesList:[{
            name:"管家",
            lable:"manager",
        },{
            name:"巡查人员",
            lable:"patrol",
        },{
            name:"维保人员",
            lable:"repair",
        },{
            name:"运维人员",
            lable:"operation",
        }],
        isUpdataPo: false,
        headers: {
          Authorization: sessionStorage.getItem('Authorization'),
          token: sessionStorage.getItem('token')
        },
        checkStrictly: false,//控制子集和父级的关系
        bindRole: {},
        isAddUpdata: 1,//1表示添加，2表示修改，3表示详情
        orgName: '',
        typeExport: 'sys_manager',
        formDataa: [],
        menuList1: [],
        showmenuList1: [],
        showmenuList: [],
        menuList: [],
        option1: [],
        xqTree: [],
        isAddorUpdate: 1,//1添加、2修改
        formSearch: {
          current: 1,
          size: 10
        },
        formData: [],//数据
        formUpdate: {},//修改表单
        total: 0,//数据总数
        pages: 0,//页面总数
        addDialog: false,
        showExport: false,
        updateDialog: false,
        dialog: false,
        formPush: {
          sex: 1,
          enable: true,
        //   orgId: []
        },
        dataTree: [],
        defaultProps: {//树状图key定义
          children: 'children',
          label: 'name'
        },
        defaultProps1: {//树状图key定义
          children: 'children',
          label: 'name'
        },
        defaultProps2: {
          children: 'children',
          label: 'name',
          value: 'id',
          expandTrigger: 'hover', checkStrictly: true
        },
        rules: {
          account: [{required: true, message: '该项不能为空'}],
          password: [{required: true, message: '该项不能为空'}],
          name: [{required: true, message: '该项不能为空'}],
          phone: [{required: true, message: '该项不能为空'}],
          enable: [{required: true, message: '该项不能为空', trigger: 'change'}],
          sex: [{required: true, message: '该项不能为空', trigger: 'change'}],
          addUser: [{required: true, message: '该项不能为空', trigger: 'change'}],
          xqId: [{required: true, message: '该项不能为空', trigger: 'change'}],
        //   orgId: [{required: true, message: '该项不能为空', trigger: 'blur'}],
        },
        imageUrl: '',
        buttonList:''
      }
    },
    methods: {
      resetPasswords(id){
        this.$confirm('是否重置用户密码为初始密码:123456', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            id:id
          }
          userReset(params).then((res) => {//
          if (res.data.ok) {
            this.$message({
            type: 'success',
            message: '重置成功!'
          });
          }else{
            this.$message({
            type: 'error',
            message: '重置失败!'
          });
          }
        })
          
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消重置'
          // });          
        });
      },
      filterTree(value, data) {
          return data.isEnable;
        },
        nodeClick({resources}) {
          this.buttonList = resources;
        },
      filterNode(value, data) {//树状图节点搜索
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      removeTag(val) {
        console.log(val)
      },
      getexportHouseUser(val) {//导出数据
        this.showExport = false
        let dataBase64 = base64.Base64
        let token = sessionStorage.getItem('tenantCode') + ":" + 49 + ":dist"
        let obj = JSON.parse(JSON.stringify(this.formSearch))
        obj.token = dataBase64.encode(token)
        obj = Object.assign(obj, val)
        obj.authorization = sessionStorage.getItem('Authorization')
        let params = this.$qs.stringify(obj)
        console.log(params)
        if (obj.excelEndPage || obj.excelBeginPage) {
          console.log(obj, obj.excelBeginPage > obj.excelEndPage)
          if (obj.excelEndPage > this.total) {
            this.$message("结束页不能大于总页数")
            return
          }
          if (obj.excelEndPage < 0 || obj.excelBeginPage < 0) {
            this.$message("页面不能为负数")
            return
          }
          if (obj.excelBeginPage > obj.excelEndPage) {
            console.log(obj)
            this.$message("起始页不能大于结束页")
            return
          }
        }
        window.self.location = exportHouseManager(params)
      },
      closeDialog(val) {
        this.showExport = false
      },
      getLabel() {//获取表头所有label
        this.showExport = true
      },
      treeClick(data) {//树状图node节点点击事件,将该节点的数据填充，修改
        console.log(data)
  
        // this.getmenuList1()
        this.getmenuList(data.id)
      },
      loadNode(node, resolve) {
        if (node.level == 0) {
          return resolve(node.data);
        }
        let data1 = node.data.data || []
        let data2 = node.data.children || []
        let data3 = [...data1, ...data2]
        setTimeout(() => {
          const data = data3;
          resolve(data);
        }, 500);
      },
      getmenuList(orgId) {//角色权限树
        console.log(orgId)
        let params = orgId
        menuList(params).then((res) => {//查询系统所有的菜单
          console.log(res)
          if (res.data.ok) {
            this.menuList1 = res.data.data
            this.$nextTick(() => this.$refs.rightsTree1.filter())
            this.huixian(orgId)
          }
        })
  
      },
      huixian(orgId) {
        bindmenuroleId(orgId).then((res) => {//角色菜单回显
          console.log(res)
          if (res.data.ok) {
            this.showmenuList1 = res.data.data
            this.$refs.rightsTree1.setCheckedKeys(this.showmenuList1);
            // this.$nextTick(() => {
            //   setTimeout(()=>{
            //     console.log(this.$refs.rightsTree1.getCheckedNodes())
            //     this.fatherCheckedObj = this.$refs.rightsTree1.getCheckedNodes().filter(item=>{
            //       item.isClicked = false//表示没有点击
            //       return item
            //     })
            //   },1000)
            // });
            // this.showmenuList = res.data.data
            // this.bindMenu.menuIds = this.showmenuList
          }
        })
      },
      getlist() {
        userListPage(this.formSearch).then((res) => {
          console.log(res)
          if (res.data.ok) {
            this.formData = res.data.data.records.filter((item) => {
              if (item.gmtCreate) {
                console.log(item.gmtCreate);
                // item.gmtCreate = getDateArray(item.gmtCreate)[9]
              }
              return item
            })
            this.total = res.data.data.total*1
          } else {
            this.$message(res.data.message);
          }
        })
      },
      getInit() {
        this.getlist()
        xqSelectList({}).then((res) => {//区域选择列表
          console.log(res)
          if (res.data.ok) {
            this.xqTree = res.data.data
          }
        })
        let org_tree = {
          name: '',
          enable: 1
        }
        orgTree(org_tree).then((res) => {//获取组织列表
          console.log(res)
          if (res.data.ok) {
            this.dataTree = res.data.data
          }
        })
      },
      handleChange(value) {
        if (value.length != 0) {
          console.log(value)
          this.formSearch.orgId = this.$refs.cascader.getCheckedNodes()[0].data.id
        } else {
          this.formSearch.orgId = ''
        }
      },
      handleChange1(value) {
        if (value.length != 0) {
          console.log(value)
          if (this.$refs.cascader.getCheckedNodes()[0].data.type != 1) {
            this.formPush.orgId = this.$refs.cascader.getCheckedNodes()[0].data.id
          } else {
            this.option1 = []
            this.formPush.orgId = ''
            this.$message("只能选择部门")
          }
  
        } else {
          this.formPush.orgId = ''
        }
      },
      updataImg(type) {//感觉type区分是添加还是修改图片
  
        if (this.imageUrl) {
  
          if (type == 1) {
            this.$nextTick(function () {
              this.$refs.addUpdata.submit();
            })
          } else {
            this.$nextTick(function () {
              this.$refs.uupdata.submit();
            })
          }
        } else {
          this.$message("请选择图片")
        }
      },
      addList(addList) {//添加树状图node节点
        // if (!this.formPush.orgId) {
        //   this.$message("请选择所属组织")
        //   return
        // }
        this.$refs[addList].validate((valid) => {
          if (valid) {
            this.addDialog = false
            userAdd(this.formPush).then((res) => {
              console.log(res)
              if (res.data.ok) {
                this.getlist()
                this.$message({
                  message: '添加成功',
                  type: 'success'
                });
  
              } else {
                this.$message('添加失败:' + res.data.message)
              }
            })
            this.addDialog = false
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      updateList(formName) {//修改
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let params = this.formUpdate
            userUpdate(params).then((res) => {
              console.log(res)
              if (res.data.ok) {
                this.$message({
                  message: '修改成功',
                  type: 'warning'
                });
                this.getlist()
              }else{
               this.$message(res.data.message)  
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
          this.updateDialog = false
        });
      },
      updateShowBox(item) {//修改东西弹窗
        // this.formUpdate = JSON.parse(JSON.stringify(item));
        this.formUpdate = {
          account:item.account,
          avatar: item.avatar,
          email: item.email,
          enable: item.enable,
          id: item.id,
          name: item.name,
          // password: item.password,
          phone: item.phone,
          roles:item.roles,
          sex: item.sex,
        }
        // this.orgName = item.orgName
        this.updateDialog = true
        this.imageUrl = item.avatar
  
        console.log(this.formUpdate, item)
      },
      deleInfor(id) {
        let params = {id:id}
        this.$confirm('确认删除吗？')
          .then(_ => {
            userDelete(params).then((res) => {
              console.log(res)
              if (res.data.ok) {
                this.$message('删除成功');
                this.getlist()
              } else {
                this.$message(res.data.message);
              }
            })
          })
          .catch(_ => {
          });
  
      },
      bindroleManage() {
  
        bindmanagerrole(this.bindRole).then((res) => {
          console.log(res)
          if (res.data.ok) {
            this.$message('绑定成功');
          } else {
            this.$message(res.data.message);
          }
          this.dialog = false
        })
      },
      showRole(obj) {//角色绑定
        this.dialog = true
        this.checkStrictly = true
        this.bindRole.managerId = obj.id
        roletreeList(obj.id).then((res) => {//权限选择列表
          console.log(res)
          if (res.data.ok) {
            this.formDataa = res.data.data
            managerrole(obj.id).then((ress) => {
              console.log(ress)
              if (ress.data.ok) {
                this.showmenuList = ress.data.data
                this.bindRole.roleIds = ress.data.data
                this.$nextTick(() => {
                  this.$refs.rightsTree.setCheckedKeys(this.showmenuList);
                  this.checkStrictly = false
                });
  
              }
            })
          }
        })
      },
      handleAvatarSuccess(res, file) {//添加头像上传成功
        console.log(res, file)
        this.imageUrl = URL.createObjectURL(file.raw);
        if (res.ok) {
          this.formPush.avatar = res.data[0]
        }
      },
      handleAvatarSuccess1(res, file) {//修改头像上传成功
        console.log(res, file)
        this.imageUrl = URL.createObjectURL(file.raw);
        if (res.ok) {
          this.formUpdate.avatar = res.data[0]
        }
      },
      onChange(file, fileList) {
        console.log(file, fileList)
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      handleCheckChange(checkedNodes, obj) {//树状图选中
        console.log(obj);
        this.bindRole.roleIds = []
        obj.checkedNodes.forEach((item) => {
          if (!item.data) {
            this.bindRole.roleIds.push(item.id)
          }
        })
        // this.bindRole.roleIds = this.$refs.rightsTree.getCheckedKeys()
        // this.bindRole.roleIds = this.$refs.rightsTree.getCheckedKeys().concat(this.$refs.rightsTree.getHalfCheckedKeys())
        console.log(this.bindRole.roleIds);
      },
      handleCurrentPage(val) {//页码改变
        this.formSearch.current = val
        this.getlist()
      },
    },
    mounted() {
      console.log(this.$root.btnControl)
      this.getInit()
    },
    components: {
      paging,
      exportInfor,
    }
  }
  </script>
  <style scoped>
  .cont_box {
    width: 100%;
    display: flex;
  }
  
  .cont_box_left, .cont_box_right {
    flex: 1;
    background: transparent;
    padding: 10px;
  }
  
  .cont_box_left {
    margin-right: 10px;
  }
  
  .margin10 {
    margin-bottom: 10px;
  }
  
  .marginRight {
    margin-bottom: 10px;
    border-bottom: 1px solid #eee;
  }
  
  .cont_box_right .el-form-item {
    margin-bottom: 20px;
  }
  
  .avatar-uploader-icon {
    line-height: 178px !important;
  }
  </style>
  